package com.normal.zbase.impl.exceptions

import android.widget.Toast
import com.normal.zbase.impl.tools.utils.ApplicationUtils
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.net.UnknownHostException

/**
 * Created by zsf on 2023/2/17 15:40
 * ******************************************
 * *
 * ******************************************
 */

/**
 * Created by zsf on 2023/2/16 14:05
 * *******************
 * 自定义异常
 * *******************
 */


//系统异常
const val CODE_UNKNOWN = "-10000"//未知
const val CODE_NO_NETWORK = "-10001"//网路异常
const val CODE_INTERRUPTED_IO = "-10002"

//自定义异常
const val CODE_SUCCESS = "0000" //请求成功
const val CODE_TOKEN_INVALID = "LGN4001000" //token 失效

data class CloudException(
    var code: String = "",
    override var message: String? = "",
    var throwable: Throwable? = null
) : Exception(message, throwable) {
    companion object {
        fun accept(throwable: Throwable): CloudException {
            return try {
                when (throwable) {
                    is UnknownHostException -> {
                        CloudException(CODE_NO_NETWORK, throwable.message, throwable)
                    }

                    is InterruptedIOException -> {
                        CloudException(CODE_INTERRUPTED_IO, throwable.message, throwable)
                    }

                    is HttpException -> {
                        CloudException(throwable.code().toString(), throwable.message, throwable)
                    }

                    is CloudException -> {
                        when (throwable.code) {
                            CODE_TOKEN_INVALID -> {//token失效
                                Toast.makeText(ApplicationUtils.context(),throwable.message,Toast.LENGTH_LONG).show()
                                CloudException(CODE_TOKEN_INVALID, throwable.message, throwable)
                            }

                            else -> {
                                Toast.makeText(ApplicationUtils.context(),throwable.message,Toast.LENGTH_LONG).show()
                                throwable
                            }
                        }
                    }

                    else -> {
                        CloudException(CODE_UNKNOWN, throwable.message ?: "", throwable)
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                CloudException(CODE_UNKNOWN, e.message ?: "", throwable)
            }
        }
    }
}
